#include <53func.h>
int main(int argc, char *argv[])
{
    // ./0_azhen_epoll 192.168.38.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET; // AF_INET ipv4
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int flag = 1; // 给SO_REUSEADDR属性的参数分配内存
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    // 赋值用具体类型 传参时强转成公共类型
    ret = bind(sockfd,(struct sockaddr *)&addr, sizeof(addr));
    // 服务端 bind 只能绑定服务端地址
    ERROR_CHECK(ret,-1,"bind");
    listen(sockfd,10);
    struct sockaddr_in client_addr;
    // client_addr_length 应该要有一个合适的初始值
    socklen_t client_addr_length = sizeof(client_addr);
    int netfd = accept(sockfd,
                       (struct sockaddr *)&client_addr,
                       &client_addr_length);
    printf("client ip = %s, port = %d\n",
           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
    char buf[4096] = {0};
    int epfd = epoll_create(1);// 创建epoll文件对象
    // 增加监听 STDIN
    struct epoll_event event; // 将来STDIN就绪，event的内容就拷贝到就绪集合
    event.events = EPOLLIN; // 读就绪
    event.data.fd = STDIN_FILENO; // 当stdin就绪时，拷贝到就绪集合里面就是stdin自己的fd
    epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&event);
    // 增加监听 netfd
    event.events = EPOLLIN|EPOLLET; // 读就绪 + 边缘触发
    event.data.fd = netfd;
    epoll_ctl(epfd,EPOLL_CTL_ADD,netfd,&event);
    ssize_t sret;
    // 给用户态的就绪集合分配内存
    struct epoll_event readyset[2];
    while(1){
        int readynum = epoll_wait(epfd,readyset,2,-1);
        printf("epoll_wait ready!\n");
        for(int i = 0; i < readynum; ++i){
            if(readyset[i].data.fd == STDIN_FILENO){
                bzero(buf,sizeof(buf));
                sret = read(STDIN_FILENO,buf,sizeof(buf));
                if(sret == 0){
                    send(netfd,"nishigehaoren",13,0);
                    goto end;                 
                }
                send(netfd,buf,strlen(buf),0);
            }
            else if(readyset[i].data.fd == netfd){
                while(1){
                    bzero(buf,sizeof(buf));
                    sret = recv(netfd,buf,3,MSG_DONTWAIT);
                    printf("sret = %ld, buf = %s\n", sret, buf);
                    if(sret == -1){
                        break;
                    }
                    if(sret == 0){
                        printf("Hehe\n");
                        goto end;
                    }
                }
                //bzero(buf,sizeof(buf));
                //sret = recv(netfd,buf,3,0);
                //if(sret == 0){
                //    printf("Hehe\n");
                //    goto end;
                //}
                //printf("buf = %s\n", buf);
            }
        }
    }
end:
    close(netfd);
    close(sockfd);
    return 0;
}

